/*
===========================================================================
This source file is part of DyLab (Dynamic Laboratory)
For the latest info, see http://dylab.googlecode.com

Copyright (c) 2006-2008 Lukas Krejci
(krejci.lukas@volny.cz)

This file is part of DyLab.

    DyLab is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    DyLab is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with DyLab.  If not, see <http://www.gnu.org/licenses/>.
===========================================================================
*/

// ============================================================================================================================
#include <dylab/utils/components/ComponentManager.h>
#include <dylab/utils/property/PropertyTree.h>
#include <dylab/utils/log/Log.h>
#include <dylab/utils/exceptions/EDoesNotExists.h>
#include <dylab/utils/exceptions/EInvalidFormat.h>

// ============================================================================================================================
void * dylab::IComponent::operator new(size_t _size)
{ 
    void * ptr = malloc(_size);
    DYLAB_ASSERT(ptr != NULL);
    return ptr;
}

void dylab::IComponent::operator delete(void * _component)
{ 
    DYLAB_ASSERT(_component != NULL);
    free(_component);
}

// ============================================================================================================================
typedef void * (__stdcall * createDylabComponent)(const char *);

// ============================================================================================================================
dylab::ComponentManager::ComponentInfo::ComponentInfo(const String & _moduleName)
: mModuleName(_moduleName)
{
}
//-----------------------------------------------------------------------------
dylab::String dylab::ComponentManager::ComponentInfo::getModuleName() const
{
    return mModuleName;
}
//-----------------------------------------------------------------------------

// ============================================================================================================================
dylab::ComponentManager::ComponentManager()
: mComponents(true)
{
}
//-----------------------------------------------------------------------------
dylab::ComponentManager::~ComponentManager()
{
    mModuleMgr.releaseAllModules();
}
//-----------------------------------------------------------------------------
void dylab::ComponentManager::setModuleBasePath(const String & _basePath)
{ 
    mModuleMgr.setBasePath(_basePath); 
}
//-----------------------------------------------------------------------------
void dylab::ComponentManager::registerComponentType(const String & _compTypeId, const String & _compTypeName)
{
    DYLAB_LOGF2("Registering component class: '%2%' (%1%)", _compTypeId, _compTypeName);
    mComponentTypeNames.insert(_compTypeId, _compTypeName);
}
//-----------------------------------------------------------------------------
dylab::String dylab::ComponentManager::translateComponentTypeIdToName(const String & _compTypeId) const
{
    String className;

    if (!mComponentTypeNames.find(_compTypeId, &className))
        throw EDoesNotExists(String::fmt("Class id %1% was not registered", _compTypeId));

    return className;
}
//-----------------------------------------------------------------------------
dylab::String dylab::ComponentManager::getComponentFullName(const String & _compTypeId, const String & _compName) const
{
    return buildComponentFullName(translateComponentTypeIdToName(_compTypeId), _compName);
}
//-----------------------------------------------------------------------------
void dylab::ComponentManager::registerComponent(const String & _moduleName, const String & _compTypeName, const String & _compName)
{ 
    String fullName = buildComponentFullName(_compTypeName, _compName);
    String fullModuleName = _moduleName + DYLAB_DYNMODULE_SUFFIX;

    DYLAB_LOGF2("Registering component '%1%' (%2%)", fullName, fullModuleName);

    mComponents.insert(fullName, new ComponentInfo(_moduleName));
}
//-----------------------------------------------------------------------------
dylab::IComponent * dylab::ComponentManager::createComponent(const String & _fullComponentName)
{
    DYLAB_LOGF("Creating component: %1%", _fullComponentName);

    ComponentInfo * compInfo = mComponents.find(_fullComponentName);
    if (compInfo == NULL)
        throw EDoesNotExists(String::fmt("Component not registered: %1%", _fullComponentName));

    DynamicModule * module = mModuleMgr.loadModule(compInfo->getModuleName());
    void * component = DYLAB_DYNMODULE_CALL(module, createDylabComponent) (_fullComponentName.c_str());
    DYLAB_ASSERT(component != NULL);
    
    return static_cast<IComponent*>( component );
}
//-----------------------------------------------------------------------------
void dylab::ComponentManager::load(const String & _fileName)
{
    PropertyTree modules;
    modules.load(_fileName);

    // set base directory for the module look-up
    setModuleBasePath(modules.getNodeValue("basePath"));

    // register the components based on info from the loaded modules config file
    for (PropertyTree::NodeList::Iterator module(*modules.getNodeList("module")); module.isValid(); module++)                            
    {
        for (PropertyTree::NodeListMap::Iterator componentList(module->getChildNodeListMap()); componentList.isValid(); componentList++)
        {
            if (componentList->getCount() != 1)
                throw EInvalidFormat(String::fmt("Invalid definition of module '%1%'", module->getValue()));
            PropertyTree::Node * component = componentList->getFirst();
            registerComponent(module->getValue(), component->getName(), component->getValue());        
        }
    }
}
//-----------------------------------------------------------------------------